import { Component } from '@angular/core';

declare var form: any;

@Component({
  templateUrl: './workday.component.html',
  styleUrls: ['./workday.component.scss']
})
export class WorkdayComponent {
  curMonth: any;
  selectedDate = new Date();

  fs: any = null;
  typeDic: any = null;

  constructor() {
    this.fs = new form.FormSimpleService('workday', {
      orderObject: { spedate: 0 },
      keyField: 'id',
      randomFields: ['id'],
      pageSize: 1000
    });
    // 加载表单数据
    this.loadData();

    // 初始化字典
    this.typeDic = new form.DictionaryService('p_workday_type');
    this.typeDic.loadAll();
  }

  // 只查询当月数据
  loadData(fun?) {
    const year = this.selectedDate.getFullYear();
    const month = this.selectedDate.getMonth() + 1;
    this.curMonth = month;
    const monthtime = month < 10 ? Number('0' + month) : month;
    const starTime = new Date(year, monthtime - 1, 1);
    const lastTime = new Date(year, monthtime, 0);
    this.fs.queryObject['spedate:>='] = starTime;
    this.fs.queryObject['spedate:<='] = lastTime;
    this.fs.loadData(true, () => {
      if (fun) {
        fun();
      }
    });
  }

  selectChange() {
    const month = this.selectedDate.getMonth() + 1;
    if (month !== this.curMonth) {
      this.loadData(() => {
        this.innerOption();
      });
    } else {
      this.innerOption();
    }
  }

  private innerOption() {
    const fo = this.fs.datas;
    let flag = true;
    for (const x of fo) {
      if (this.dateToString(new Date(x.spedate)) === this.dateToString(this.selectedDate)) {
        flag = false;
        break;
      }
    }
    // 没有数据
    if (flag) {
      this.fs.innerAddRow();
      this.fs.er.spedate = this.selectedDate;
      this.fs.er.type = 1;
      this.fs.save();
    }
  }

  // 日历控件判断
  getSpedate(spedate, date) {
    if (this.dateToString(new Date(spedate)) === this.dateToString(date)) {
      return true;
    }
  }

  // 转换为年月日做判断
  private dateToString(date: Date) {
    const year = date.getFullYear();
    let month = (date.getMonth() + 1).toString();
    let day = (date.getDate()).toString();
    if (month.length === 1) {
      month = '0' + month;
    }
    if (day.length === 1) {
      day = '0' + day;
    }
    const dateTime = year + '-' + month + '-' + day;
    return dateTime;
  }
}
